<?php
namespace Admin\Controller;
use Lib\Api\OrderApi;
use Think\Controller;
use Think\Model;
class OrderController extends Controller {
    private $modelName = 'Order';

    public function index(){
        $this->display();
    }

    public function current_order() {
        if (!empty($_GET['date'])) {
            $this->assign('d', $_GET['date']);
        } else {
            $modelObj = M($this->modelName);
            $date = $modelObj->where(array("type"=>0))->min('begin_time');
            if (empty($date)) {
                $this->assign('d', date('Y-m-d'));
            } else {
                // $dates = explode(' ', $date);
                $this->assign('d', $date);
            }
        }
        $this->display();
    }

    public function history_order() {
        if (!empty($_GET['date'])) {
            $this->assign('d', $_GET['date']);
        } else {
            /*$modelObj = M($this->modelName);
            $date = $modelObj->min('begin_time');
            if (empty($date)) {
                $this->assign('d', date('Y-m-d'));
            } else {
               // $dates = explode(' ', $date);
                $this->assign('d', $date);
            }*/
            $this->assign('d', date('Y-m-d'));
        }
        $this->display();
    }

    public function tolist() {
		$loadType = $_POST['loadType'];
        if ($loadType == 1 && session('admin_id') != 1) {
            $RefreshTime = C("RefreshTime");
            if (!empty(session("order_tolist"))) {
                $start_time = session("order_tolist");
                $end_time = date('Y-m-d H:i:s');
                if ((strtotime($end_time) - strtotime($start_time)) <= $RefreshTime) {
                    $data['RefreshTime'] = $RefreshTime - (strtotime($end_time) - strtotime($start_time));
                    // $data['RefreshTime'] = '查询速度太快了，请先休息一下吧';
                    $this->ajaxReturn($data);
                } else {
                    session("order_tolist", date('Y-m-d H:i:s'));
                }
            } else {
                session("order_tolist", date('Y-m-d H:i:s'));
            }
        }
		
        $page_size = $_POST['page_size'];
        $page_num = $_POST['page_num'];
        // $keyword = $_POST['keyword'];
        $type = $_POST['type'];
        $data_cycle = $_POST['data_cycle'];

        $nick_name = $_POST['nick_name'];
        $mobile_phone = $_POST['mobile_phone'];
        $agent_id = $_POST['agent_id'];
        $belong_organization_id = $_POST['organization_id'];
        $play_type = $_POST['play_type'];
		
		$sortKey = $_POST['sortKey'];
        $sort = $_POST['sort'];

        $search_date = explode('/', $data_cycle);
        $begin_date = $search_date[0] . " 04:00";
        $end_date = $search_date[1] . " 04:00";

        $organization_id = session('admin_id');

        $where_and_arr = array();
        $where_or_arr = array();
        $map = array();
        if ($nick_name != "") {
            $map['b.nick_name']  = array('like', '%'.$nick_name.'%');
            $where_or_arr[] = "b.nick_name like '%".$nick_name."%'";
        }
        if ($mobile_phone != "") {
            $map['b.mobile_phone']  = array('like', '%'.$mobile_phone.'%');
            $where_or_arr[] = "b.mobile_phone like '%".$mobile_phone."%'";
        }
        if ($play_type != 0) {
            $map['a.play_type']  = array('eq', $play_type);
            $where_or_arr[] = "a.play_type = ".$play_type;
        }
        if ($agent_id > 0) {
            $map['b.recommend_id']  = array('eq', $agent_id);
            $where_or_arr[] = "b.recommend_id = ".$agent_id;
        } else if ($belong_organization_id != '') {
            $where['ub.organization_id']  = array('in', $belong_organization_id);
            $where_and_arr[] = "ub.organization_id in (".$belong_organization_id.")";
        } else {
            $where["ub.organization_id"] = $organization_id;
            $where_and_arr[] = "ub.organization_id = ".$organization_id;
        }
        if (count($map) > 0) {
            $map['_logic'] = 'or';
            $where['_complex'] = $map;
        }

        if ($type == 1) {
            $where['a.state'] = 0;
            $where_and_arr[] = "a.state = 0";
        } else {
            $where['a.state'] = array("gt", 0);
            $where_and_arr[] = "a.state != 0";
        }
        $where['DATE_FORMAT(a.begin_time, "%Y-%m-%d %H:%i")'] = array(array('egt', $begin_date), array('elt',$end_date));
        $where_and_arr[] = "DATE_FORMAT(a.begin_time, \"%Y-%m-%d %H:%i\") >= '".$begin_date."' and DATE_FORMAT(a.begin_time, \"%Y-%m-%d %H:%i\") <= '".$end_date."'";

        $field = 'a.*, ifnull(b.nick_name, "未填写") nick_name, b.mobile_phone, c.fee_money, c.money, ifnull(o.name, "--") as deal_organization, ifnull(agent.name, "--") as agent_name';

        $left = 'left join fs_user b on b.id = a.user_id';
        $left .= ' left join fs_trade_detail c on c.out_trade_no = a.order_no and (c.type = 2 or c.type = 3 or c.type = 4)';
        $left .= ' left join fs_user_belong ub on ub.user_id = b.id and DATE_FORMAT(ub.datetime, "%Y-%m-%d %H:%i:%s") <= DATE_FORMAT(a.begin_time, "%Y-%m-%d %H:%i:%s") and ub.state=1';
        $left .= ' left join fs_user_belong uub on uub.user_id = b.id and DATE_FORMAT(uub.datetime, "%Y-%m-%d %H:%i:%s") <= DATE_FORMAT(a.begin_time, "%Y-%m-%d %H:%i:%s") and uub.organization_level = 1';
        $left .= ' left join fs_organization o on o.id = uub.organization_id';
        $left .= ' left join fs_agent agent on agent.id = b.recommend_id';

        $AGENTCONFIG = C('AGENTCONFIG');
        for($i=1; $i<(count($AGENTCONFIG)-2); $i++) {
            $field .= ',ifnull(u'.$i.'.name, "--") as p_'.$i.'name';
            $left .= ' left join fs_user_belong ub'.$i.' on ub'.$i.'.user_id = a.user_id and ub'.$i.'.organization_level = '.$i . ' and ub'.$i.'.state=1';
            $left .= ' left join fs_organization u'.$i.' on u'.$i.'.id = ub'.$i.'.organization_id';
        }

        $group = 'a.order_no';

        if (!empty($sortKey) && !empty($sort)) {
            if (!empty($sortKey) && !empty($sort)) {
				if ($sortKey == 'gain_price') {
					$order = 'CONVERT(a.'.$sortKey.',SIGNED) '.$sort;
				} else {
					$order = 'a.'.$sortKey.' '.$sort;
				}

			} else {
				$order = 'a.begin_time desc';
			}
        } else {
            $order = 'a.begin_time desc';
        }
        $list = OrderApi::getList($where, $left, $page_num, $page_size, $field, $order, $group);

        /*$left = 'left join fs_user b on b.id = a.user_id';
        $left .= ' left join fs_user_belong ub on ub.user_id = b.id and DATE_FORMAT(ub.datetime, "%Y-%m-%d %H:%i:%s") <= DATE_FORMAT(a.begin_time, "%Y-%m-%d %H:%i:%s")';
        $total = OrderApi::getTotal($where, $left);*/

        $where_str = "";
        if (count($where_and_arr) > 0 || count($where_or_arr) > 0) {
            $where_str = " where ";
            if (count($where_and_arr) > 0) {
                $where_str .= implode(" and ", $where_and_arr);
            }
            if (count($where_or_arr) > 0) {
                if (count($where_and_arr) > 0) {
                    $where_str .= " and ";
                }
                $where_str .= "(".implode(" or ", $where_or_arr).")";
            }
        }

        $model = M();
        $sql = "select count(t.id) total from (select a.id from fs_order a";
        $sql .= " left join fs_user b on b.id = a.user_id";
        $sql .= " left join fs_user_belong ub on ub.user_id = b.id and DATE_FORMAT(ub.datetime, \"%Y-%m-%d %H:%i:%s\") <= DATE_FORMAT(a.begin_time, \"%Y-%m-%d %H:%i:%s\") and ub.state=1";
        $sql .= $where_str; // " where a.state != 0 and ub.organization_id = 1 group by a.order_no";
        $sql .= " group by a.order_no) t";
        $total = $model->query($sql);

        $data = pageHelper($page_size, $page_num, $list, $total[0]['total']);
        $data['c'] = $AGENTCONFIG;
        $name_arr = array();
        for($i=1; $i<(count($AGENTCONFIG)-1); $i++) {
            if($AGENTCONFIG[$i]['type'] != 3) {
                $name_arr[] = $AGENTCONFIG[$i]['name'];
            }
        }
        $data['name_arr'] = $name_arr;

        $value_arr = array();
        for($i=1; $i<(count($AGENTCONFIG)-2); $i++) {
            if($AGENTCONFIG[$i]['type'] != 3) {
                $value_arr[] = $i;
            }
        }
        $data['value_arr'] = $value_arr;

        $model = M();
        $sql = "select ifnull(sum(t.mun), 0) as sum_mun, ifnull(sum(t.real_price), 0) as sum_real_price";
        $sql .= ",ifnull(sum((t.order_fee/100)*(t.real_price*t.mun-t.voucher_price)), 0) as sum_fee_money, ifnull(sum(t.gain_price), 0) as sum_gain_price";
        $sql .= ",ifnull(sum(t.order_price-t.voucher_price), 0) as sum_order_price";
        $sql .= " from (select a.mun, a.real_price, a.order_fee, a.voucher_price, a.gain_price, a.order_price from fs_order a";
        $sql .= " left join fs_user b on b.id = a.user_id";
        $sql .= " left join fs_user_belong ub on ub.user_id = b.id and DATE_FORMAT(ub.datetime, \"%Y-%m-%d %H:%i:%s\") <= DATE_FORMAT(a.begin_time, \"%Y-%m-%d %H:%i:%s\") and ub.state=1";
        $sql .= $where_str; // " where a.state != 0 and ub.organization_id = 1 group by a.order_no";
        $sql .= " group by a.order_no) t";
        $sum = $model->query($sql);
        $data['sum'] = $sum[0];

        $this->ajaxReturn($data);
    }

    public function exportexcel() {
        //引入PHPExcel库文件
        // Vendor('PHPExcel.Classes.PHPExcel');

        $type = $_POST['type'];
        $data_cycle = $_POST['data_cycle'];
        $nick_name = $_POST['nick_name'];
        $mobile_phone = $_POST['mobile_phone'];
        $agent_id = $_POST['agent_id'];
        $belong_organization_id = $_POST['organization_id'];
        $play_type = $_POST['play_type'];

        //表格数组
        $users = $this->getData($data_cycle,$nick_name, $mobile_phone, $agent_id, $belong_organization_id, $type, $play_type);
        $data = array();
        for ($i=0; $i<count($users); $i++) {
            $user = array(
                ($i+1), $users[$i]["nick_name"], $users[$i]["mobile_phone"],$users[$i]["operation_center"],$users[$i]["member_unit"],$users[$i]["micro_ring"],
                $users[$i]["agent_name"],$users[$i]["balance"],$users[$i]["datetime"],$users[$i]["login_ip"],$users[$i]["last_login"]
            );
            array_push($data, $user);
        }

        import("Org.Util.PHPExcel");
        //创建对象
        $excel = new \PHPExcel();
        //Excel表格式,这里简略写了8列
        $letter = array('A','B','C','D','E','F','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
        //表头数组
        $tableheader = array('#','订单编号','客户', '运营中心', '会员单位', '微圈', '经纪人', '货币&规格', '涨&跌', '手数', '定金', '交易额', '点数', '建仓价格', '平仓价格', '平仓时间', '手续费', '平仓盈利', '成交机构');
        //填充表头信息
        for($i = 0;$i < count($tableheader);$i++) {
            $excel->getActiveSheet()->setCellValue("$letter[$i]1","$tableheader[$i]");
        }
        //填充表格信息
        for ($i = 2;$i <= count($data) + 1;$i++) {
            $j = 0;
            foreach ($data[$i - 2] as $key=>$value) {
                $excel->getActiveSheet()->setCellValue("$letter[$j]$i","$value");
                $j++;
            }
        }

        $fileName = "users";
        $date = date("Y_m_d",time());
        $fileName .= "_{$date}.xls";
        $fileName = iconv("utf-8", "gb2312", $fileName);

        //创建Excel输入对象
        $write = new \PHPExcel_Writer_Excel5($excel);
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");;
        header('Content-Disposition:attachment;filename="'.$fileName.'"');
        header("Content-Transfer-Encoding:binary");
        $write->save('php://output');
    }

    public function changeOperateType() {
        $modelObj = M($this->modelName);
        $rel = $modelObj->where(array('id' => $_POST['id']))->find();
        if (!empty($rel)) {
            $begin_time = strtotime($rel['begin_time']);
            $end_time = strtotime(date('Y-m-d H:i:s'));
            if (($end_time - $begin_time) >=  60) {
                $this->ajaxReturn('-1');
            } else if (($end_time - $begin_time) >=  50) {
                $this->ajaxReturn('2');
            } else {
                $this->ajaxReturn($modelObj->save($modelObj->create($_POST, Model::MODEL_UPDATE)));
            }
        }
    }

    public function toTradeInfo() {
        $modelObj = M('Order');
        // $data = $modelObj->where(array('id' => $_POST['id']))->find();

        $field = "a.*,b.game_name,c.profit_rate";
        $data = $modelObj->table('fs_order a')
            ->join('left join fs_game_type b on b.id = a.play_type left join fs_game_type_profit c on c.trade_time = a.trade_time')
            ->field($field)
            ->where(array('a.id' => $_POST['id']))
            ->find();

        $ajaxdata['data'] = $data;
        $this->ajaxReturn($ajaxdata);
    }

    private function getData($data_cycle,$nick_name,$mobile_phone,$agent_id,$belong_organization_id, $type, $play_type) {

        $search_date = explode('/', $data_cycle);
        $begin_date = $search_date[0];
        $end_date = $search_date[1];

        $organization_id = session('admin_id');

        $map = array();
        if ($nick_name != "") {
            $map['b.nick_name']  = array('like', '%'.$nick_name.'%');
        }
        if ($mobile_phone != "") {
            $map['b.mobile_phone']  = array('like', '%'.$mobile_phone.'%');
        }
        if ($play_type != 0) {
            $map['a.play_type']  = array('eq', $play_type);
        }
        if ($agent_id > 0) {
            $map['b.recommend_id']  = array('eq', $agent_id);
        } else if ($belong_organization_id != '') {
            $map['ub.organization_id']  = array('in', $belong_organization_id);
        } else {
            $where["ub.organization_id"] = $organization_id;
        }
        if (count($map) > 0) {
            $map['_logic'] = 'or';
            $where['_complex'] = $map;
        }

        if ($type == 1) {
            $where['a.state'] = 0;
        } else {
            $where['a.state'] = array("gt", 0);
        }
        $where['DATE_FORMAT(a.begin_time, "%Y-%m-%d")'] = array(array('egt', $begin_date), array('elt',$end_date));

        $field = 'a.*, ifnull(b.nick_name, "未填写") nick_name, b.mobile_phone, c.fee_money, c.money, ifnull(o.name, "--") as deal_organization, ifnull(agent.name, "--") as agent_name';

        $left = 'left join fs_user b on b.id = a.user_id';
        $left .= ' left join fs_trade_detail c on c.out_trade_no = a.order_no and (c.type = 2 or c.type = 3 or c.type = 4)';
        $left .= ' left join fs_user_belong ub on ub.user_id = b.id and DATE_FORMAT(ub.datetime, "%Y-%m-%d %H:%i:%s") <= DATE_FORMAT(a.begin_time, "%Y-%m-%d %H:%i:%s")';
        $left .= ' left join fs_user_belong uub on uub.user_id = b.id and DATE_FORMAT(uub.datetime, "%Y-%m-%d %H:%i:%s") <= DATE_FORMAT(a.begin_time, "%Y-%m-%d %H:%i:%s") and uub.organization_level = 1';
        $left .= ' left join fs_organization o on o.id = uub.organization_id';
        $left .= ' left join fs_agent agent on agent.id = b.recommend_id';

        $AGENTCONFIG = C('AGENTCONFIG');
        for($i=1; $i<(count($AGENTCONFIG)-2); $i++) {
            $field .= ',ifnull(u'.$i.'.name, "--") as p_'.$i.'name';
            $left .= ' left join fs_user_belong ub'.$i.' on ub'.$i.'.user_id = a.user_id and ub'.$i.'.organization_level = '.$i;
            $left .= ' left join fs_organization u'.$i.' on u'.$i.'.id = ub'.$i.'.organization_id';
        }

        $group = 'a.order_no';

        $order = 'a.begin_time desc';
        $list = OrderApi::getListAllByCondition($where, $left, $field, $order, $group);
        return $list;
    }
}